const knex = require("../../db/knex")
const resetTableId = require("../../utils/resetTableId");


async function deleteOperation(id) {
    //
    try {
        await knex.transaction(async (trx) => {

            let deleteQuestionnaire = await trx('save_questionnaire').del().where({id: id})//删除对应id的问卷基础信息
            let selectQuestionToDel = await trx('question_list').select('*').where({questionnaire_id: id})//寻找要删除的问题
            let QuestionIdToDel = Array.from(selectQuestionToDel).map(o => { //删除的问题的id
                return o.id
            })
            console.log(selectQuestionToDel, '删除问题的id')
            let deleteQuestions = await trx('question_list').del().where({questionnaire_id: id})//删除对应问卷的问题
            for (const o of QuestionIdToDel) { //根据问题id删除对应的选项
                let deleteOptions = await trx('option_list').del().where({questionnaire_id: id})
            }

        })
    } catch (e) {
        console.log(e)
    }
}

async function deleteQuestionnaire(params, res) {
    let {id} = params
    let isErr = false
    await knex.transaction(async trx => {
        //先查看该问卷是否已发布,已发布则不能删除
        let isPublished = await trx('published_questionnaire').select('*').where({questionnaire_id: id})
        if (isPublished.length > 0) {
            isErr = true
        }
    })
    if (isErr) {
        res.sendStatus(409)
        return
    }
    try {
        await deleteOperation(id)
        res.send({
            msg: '删除成功'
        })
    } catch (e) {
        console.log(e)
        throw e
    } finally {
        await resetTableId("question_list", "id")
    }

}

module.exports = {deleteQuestionnaire, deleteOperation}
